package com.gitee.chili.leisure.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class TaskExecutorConfig {

    /** 核心线程数 */
    @Value("${spring.task.pool.corePoolSize}")
    private Integer corePoolSize;

    /** 最大线程数 */
    @Value("${spring.task.pool.maxPoolSize}")
    private Integer maxPoolSize;

    /** 队列容量 */
    @Value("${spring.task.pool.queueCapacity}")
    private Integer queueCapacity;

    /** 线程活跃时间（秒） */
    @Value("${spring.task.pool.keepAliveSeconds}")
    private Integer keepAliveSeconds;

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix("AsyncService-start-executor-");
        // 核心线程超时关闭
        executor.setAllowCoreThreadTimeOut(true);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}